import MyTable from '@/component/common/myTable'
import TableSelects from '@/component/common/tableSelects/tableSelects'
import { Button, Flex, Input, Popconfirm } from 'antd'
import { useEffect, useMemo, useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import paperApi from '../api/index'
import { useMessageApi } from '@/component/context/messageContext/message'

export default function ExamPaperList() {
  const [searchParams, setSearchParams] = useState({
    pageNum: 1,
    pageSize: 20,
    name: '',
  })
  const location = useLocation()
  const navigate = useNavigate()
  const messageApi = useMessageApi()
  const [loading, setLoading] = useState<boolean>(false)
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([])
  const [questionState, setQuestionState] = useState({
    tableData: [],
    total: 0,
  })
  // 过滤器组件
  const Filter = () => {
    const tableOptions = [
      {
        render: (
          <Input
            key="name"
            placeholder="请输入试卷名"
            value={searchParams.name}
            allowClear
            onChange={(e) => {
              setSearchParams((oldV) => {
                return { ...oldV, name: e.target.value }
              })
            }}
          />
        ),
      },
    ]
    return (
      <TableSelects
        options={tableOptions}
        source={searchParams}
        onSearch={() => {
          navigate({
            search: `?pageNum=${searchParams.pageNum}&pageSize=${searchParams.pageSize}&name=${searchParams.name}`,
          })
        }}
        buttonChildren={
          <Flex gap={'10px'}>
            {selectedRowKeys.length > 0 && (
              <Popconfirm
                title={`确定删除这 ${selectedRowKeys.length} 张试卷吗？`}
                onConfirm={() => {
                  delExamPaper(selectedRowKeys)
                }}>
                <Button>删除</Button>
              </Popconfirm>
            )}
            <Button
              onClick={() => {
                navigate('/home/exam/add')
              }}>
              添加
            </Button>
          </Flex>
        }></TableSelects>
    )
  }

  const getPaperList = (params: any) => {
    paperApi.getPaperList(params).then((data: any) => {
      setQuestionState((oldV) => {
        return {
          ...oldV,
          tableData: data.ques.map((item: any) => {
            return { ...item, content: JSON.parse(item.content) }
          }),
          total: data.total,
        }
      })
      setTimeout(() => {
        setLoading(false)
      }, 300)
    })
  }

  const delExamPaper = (ids: Array<number>) => {
    paperApi.delTestPaper(ids).then((res) => {
      messageApi.success('删除成功')
      getPaperList(searchParams)
    })
  }

  // 监听URL参数变化
  useEffect(() => {
    const searchParams = new URLSearchParams(location.search)
    const params = {
      pageNum: searchParams.get('pageNum')
        ? Number(searchParams.get('pageNum'))
        : 1,
      pageSize: searchParams.get('pageSize')
        ? Number(searchParams.get('pageSize'))
        : 20,
      name: searchParams.get('name') ? String(searchParams.get('name')) : '',
    }
    setSearchParams(params)
    getPaperList(params)
  }, [location.search])

  // 表格组件
  const Table = useMemo(() => {
    const rowSelection = {
      onChange: (selectedRowKeys: any) => {
        setSelectedRowKeys(selectedRowKeys)
      },
      getCheckboxProps: (record: any) => ({
        disabled: false,
      }),
    }
    const columns: any = [
      {
        title: '名称',
        dataIndex: 'name',
        key: 'name',
        align: 'center',
      },
      {
        title: '总分',
        dataIndex: 'score',
        key: 'score',
        align: 'center',
      },
    ]
    return (
      <MyTable
        loading={loading}
        rowSelection={rowSelection}
        rowKey={(record) => record.id}
        dataSource={questionState?.tableData}
        columns={columns}
        pageSize={searchParams.pageSize}
        total={questionState.total}
        onPaginationChange={(pageNum, pageSize) => {
          navigate({
            search: `?pageNum=${pageNum}&pageSize=${pageSize}`,
          })
        }}
        onRow={(record) => ({
          onClick: () => {
            navigate(`/home/exam/show/${record.id}`)
          },
        })}></MyTable>
    )
  }, [
    loading,
    navigate,
    questionState?.tableData,
    questionState.total,
    searchParams.pageSize,
  ])

  return (
    <>
      {Filter()}
      {Table}
    </>
  )
}
